package com.lvmama.pangolin.timer.processor;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lvmama.pangolin.busi.config.ConfigManager;
import com.lvmama.pangolin.common.Constant;
import com.lvmama.pangolin.common.DateUtil;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.entity.MissProduct;
import com.lvmama.pangolin.entity.Timer;
import com.lvmama.pangolin.entity.hotel.HotelPdetail;
import com.lvmama.pangolin.entity.lmm.LMMCareProduct;
import com.lvmama.pangolin.entity.mt.TicketPdetailMt;
import com.lvmama.pangolin.entity.spider.TicketProduct;
import com.lvmama.pangolin.hotel.service.HotelPdetailService;
import com.lvmama.pangolin.lmm.service.LMMCareProductService;
import com.lvmama.pangolin.mt.service.TicketPdetailMtService;
import com.lvmama.pangolin.qnr.service.QNRTicketCommodityService;
import com.lvmama.pangolin.service.MissProductService;
import com.lvmama.pangolin.tc.service.TCTicketCommodityService;
import com.lvmama.pangolin.tn.service.TNTicketCommodityService;
import com.lvmama.pangolin.util.SpringContextUtil;
import com.lvmama.pangolin.xc.service.XCTicketCommodityService;

@Service
public class CheckSpiderDate
{
	@Autowired
	private  LMMCareProductService careProductService;
	@Autowired
	private  QNRTicketCommodityService qnrTicketService;
	@Autowired
	private  TCTicketCommodityService tcTicketService;
	@Autowired
	private  XCTicketCommodityService xcTicketService;
	@Autowired
	private  TNTicketCommodityService tnTicketService;
	@Autowired
	private  TicketPdetailMtService mtTicketService;
	@Autowired
	private  MissProductService missProductService;
	@Autowired
	private  HotelPdetailService hotelPdetailService;
	
	private Logger logger = Logger.getLogger(CheckSpiderDate.class);
	
	public void checkSpider(List<Timer> timerList) throws Exception
	{
		logger.info("检查抓取情况开始...");
		if(timerList != null && timerList.size() > 0)
		{
			if(careProductService == null)
			{
				careProductService = (LMMCareProductService) SpringContextUtil.getBean(LMMCareProductService.class);
			}
			List<LMMCareProduct> careList = careProductService.getAll(null,null,null,null);
			Map<String,List<LMMCareProduct>> map = new HashMap<String,List<LMMCareProduct>>();
			if(careList != null && !careList.isEmpty())
			{
				List<LMMCareProduct> list = null;
				String cityCode = null;
				String busiCode = null;
				for (LMMCareProduct lmmCareProduct : careList)
				{
					cityCode = lmmCareProduct.getCityCode();
					busiCode  = lmmCareProduct.getBusinessCode();
					
					list = map.get(busiCode + "_" +cityCode);
					if(list == null )
					{
						list = new ArrayList<LMMCareProduct>();
						list.add(lmmCareProduct);
						map.put(busiCode + "_" +cityCode, list);
					}
					else
					{
						list.add(lmmCareProduct);
					}
				}
			}
			String city = null;
			String taskId = null;
			String paramCode = null;
			Date taskDate = null;
			String companyCode = null;
			String businessCode = null;
			ConfigManager config = ConfigManager.getInstance();
			Map<String, Object> paramMap = new HashMap<String, Object>();
			Map<String, String> paramMap2 = new HashMap<String, String>();
			List<TicketProduct> pist = null;
			for (Timer timer : timerList)
			{
				if(!"PYTHON".equals(timer.getTimer_type()))
				{
					continue;
				}
				Date date = timer.getCreate_time();
				Date currentDate = new Date();
				String cron = timer.getTimer_cron();
				Date cronDate = DateUtil.getDateFromCron(cron);
				//当天的抓取任务才能重跑url
				if(DateUtil.sameDate(date, currentDate) || DateUtil.sameDate(cronDate, currentDate))
				{
					city = timer.getGranularity_value();
					taskId = timer.getTask_id();
					paramCode = timer.getTimer_param();
					taskDate = timer.getCreate_time();
					
					companyCode = config.getParamValue(timer.getTimer_param(), "COMPANY_CODE");
					businessCode = config.getParamValue(timer.getTimer_param(), "BUSINESS_CODE","TICKET");
					List<LMMCareProduct> cityCareList = map.get(businessCode + "_" + city);
					paramMap.put("task_id",taskId);
					paramMap.put("city_code",city);
					//mt命名是taskId cityCode，后面优化
					paramMap2.put("taskId",taskId);
					paramMap2.put("cityCode",city);
					List<MissProduct> missList = null;
					if("TICKET".equals(businessCode))
					{
						if("tc".equals(companyCode))
						{
							if(tcTicketService == null)
							{
								tcTicketService = (TCTicketCommodityService) SpringContextUtil.getBean(TCTicketCommodityService.class);
							}
							pist = tcTicketService.queryCommodityListByTaskID(paramMap);
							
						}
						else if("xc".equals(companyCode))
						{
							if(xcTicketService == null)
							{
								xcTicketService = (XCTicketCommodityService) SpringContextUtil.getBean(XCTicketCommodityService.class);
							}
							pist = xcTicketService.queryCommodityListByTaskID(paramMap);
						}
						else if("tn".equals(companyCode))
						{
							if(tnTicketService == null)
							{
								tnTicketService = (TNTicketCommodityService) SpringContextUtil.getBean(TNTicketCommodityService.class);
							}
							pist = tnTicketService.queryCommodityListByTaskID(paramMap);
						}
						else if("qnr".equals(companyCode))
						{
							if(qnrTicketService == null)
							{
								qnrTicketService = (QNRTicketCommodityService) SpringContextUtil.getBean(QNRTicketCommodityService.class);
							}
							pist = qnrTicketService.queryCommodityListByTaskID(paramMap);
						}
						else if("mt".equals(companyCode))
						{
							List<TicketPdetailMt> list = mtTicketService.findListByMap(paramMap2);
							pist = exchange(list);
						}
						missList =  checkMissProduct(cityCareList,companyCode,pist,taskId,taskDate,paramCode);
						
					}
					else if ("HOTEL".equals(businessCode))
					{
						if(hotelPdetailService == null)
						{
							hotelPdetailService = (HotelPdetailService) SpringContextUtil.getBean(HotelPdetailService.class);
						}
						Map<String, String> param = new HashMap<String, String>();
						param.put("taskId",taskId);
						param.put("cityCode",city);
						if("tc".equals(companyCode))
						{
							param.put("companyCode", Constant.TC_C_CODE);
						}
						else if("xc".equals(companyCode))
						{
							param.put("companyCode", Constant.XC_C_CODE);
						}
						else if("tn".equals(companyCode))
						{
							param.put("companyCode", Constant.TN_C_CODE);
						}
						else if("qnr".equals(companyCode))
						{
							param.put("companyCode", Constant.QNR_C_CODE);
						}
						else if("el".equals(companyCode))
						{
							param.put("companyCode", Constant.EL_C_CODE);
						}
						List<HotelPdetail> hotelList = hotelPdetailService.findListByMap(param);
						missList = checkHotelMissProduct(cityCareList,companyCode,hotelList,taskId,taskDate,paramCode);
						
					}
					if(missList != null && !missList.isEmpty())
					{
						for (MissProduct record : missList)
						{
							missProductService.insertSelective(record);
						}
						
					}
				}
				
			}
			
		}
		
		logger.info("检查抓取情况结束...");
	}
	
	private List<TicketProduct> exchange(List<TicketPdetailMt> list) {
		if(list==null || list.isEmpty()){
			return null;
		}
		List<TicketProduct> pist = new ArrayList<>();
		for(TicketPdetailMt item:list){
			TicketProduct ticketProduct = new TicketProduct();
			ticketProduct.setDetail_url(item.getDetailUrl());
			ticketProduct.setScenery_name(item.getSceneryName());
			ticketProduct.setLv_product_id(item.getLvProductId());
			pist.add(ticketProduct);
		}
		return pist;
	}

	private List<MissProduct> checkMissProduct(List<LMMCareProduct> careList,String companyCode,List<TicketProduct> spiderList
			,String taskId,Date taskDate,String paramCode)
	{
		List<MissProduct> list = new ArrayList<MissProduct>();
		
		if(careList != null && !careList.isEmpty())
		{
			String url = null;
			String name = null;
			String lvp = null;
			for (LMMCareProduct careProduct : careList)
			{
				lvp = careProduct.getProductId();
				if("tc".equals(companyCode))
				{
					url = careProduct.getTc_url();
					name = careProduct.getTc_name();
					
				}
				else if("xc".equals(companyCode))
				{
					url = careProduct.getXc_url();
					name = careProduct.getXc_name();
				}
				else if("tn".equals(companyCode))
				{
					url = careProduct.getTn_url();
					name = careProduct.getTn_name();
				}
				else if("qnr".equals(companyCode))
				{
					url = careProduct.getQnr_url();
					name = careProduct.getQnr_name();
				}
				else if("mt".equals(companyCode))
				{
					url = careProduct.getMt_url();
					name = careProduct.getMt_name();
				}
				boolean spiderFlag = false;
				if(!StringTools.isValid(url))
				{
					spiderFlag = true;
				}
				if(spiderList != null && !spiderList.isEmpty())
				{
					for (TicketProduct product : spiderList)
					{
						if(url != null && url.equalsIgnoreCase(product.getDetail_url()))
						{
							spiderFlag = true;
						}
						if(name != null && name.equalsIgnoreCase(product.getScenery_name()))
						{
							spiderFlag = true;
						}
						if(lvp != null && lvp.equalsIgnoreCase(product.getLv_product_id()))
						{
							spiderFlag = true;
						}
						
					}
				}
				if(!spiderFlag)
				{
					MissProduct missProduct = new MissProduct();
					missProduct.setBusinessCode(careProduct.getBusinessCode());
					missProduct.setCityCode(careProduct.getCityCode());
					missProduct.setCityName(careProduct.getCityName());
					missProduct.setCompanyCode(companyCode);
					missProduct.setDealFlag(0);
					missProduct.setProductId(lvp);
					missProduct.setProductName(careProduct.getProductName());
					missProduct.setName(name);
					missProduct.setUrl(url);
					Date date =  new Date();
					missProduct.setInsertTime(new Timestamp(date.getTime()));
					missProduct.setUpdateTime(new Timestamp(date.getTime()));
					missProduct.setTaskDate(taskDate);
					missProduct.setTaskId(taskId);
					missProduct.setParamCode(paramCode);
					list.add(missProduct);
					
				}
			}
			
		}
		
		return list;
	}
	
	private List<MissProduct> checkHotelMissProduct(List<LMMCareProduct> careList,String companyCode,List<HotelPdetail> spiderList
			,String taskId,Date taskDate,String paramCode)
	{
		List<MissProduct> list = new ArrayList<MissProduct>();
		
		if(careList != null && !careList.isEmpty())
		{
			String url = null;
			String name = null;
			String lvp = null;
			for (LMMCareProduct careProduct : careList)
			{
				lvp = careProduct.getProductId();
				if("tc".equals(companyCode))
				{
					url = careProduct.getTc_url();
					name = careProduct.getTc_name();
					
				}
				else if("xc".equals(companyCode))
				{
					url = careProduct.getXc_url();
					name = careProduct.getXc_name();
				}
				else if("tn".equals(companyCode))
				{
					url = careProduct.getTn_url();
					name = careProduct.getTn_name();
				}
				else if("qnr".equals(companyCode))
				{
					url = careProduct.getQnr_url();
					name = careProduct.getQnr_name();
				}
				else if("el".equals(companyCode))
				{
					url = careProduct.getYl_url();
					name = careProduct.getYl_name();
				}
				boolean spiderFlag = false;
				if(!StringTools.isValid(url))
				{
					spiderFlag = true;
				}
				if(spiderList != null && !spiderList.isEmpty())
				{
					for (HotelPdetail product : spiderList)
					{
						if(url != null && url.equalsIgnoreCase(product.getDetailUrl()))
						{
							spiderFlag = true;
						}
						if(name != null && name.equalsIgnoreCase(product.getHotelName()))
						{
							spiderFlag = true;
						}
						if(lvp != null && lvp.equalsIgnoreCase(product.getLvProductId()))
						{
							spiderFlag = true;
						}
						
					}
				}
				if(!spiderFlag)
				{
					MissProduct missProduct = new MissProduct();
					missProduct.setBusinessCode(careProduct.getBusinessCode());
					missProduct.setCityCode(careProduct.getCityCode());
					missProduct.setCityName(careProduct.getCityName());
					missProduct.setCompanyCode(companyCode);
					missProduct.setDealFlag(0);
					missProduct.setProductId(lvp);
					missProduct.setProductName(careProduct.getProductName());
					missProduct.setName(name);
					missProduct.setUrl(url);
					Date date =  new Date();
					missProduct.setInsertTime(new Timestamp(date.getTime()));
					missProduct.setUpdateTime(new Timestamp(date.getTime()));
					missProduct.setTaskDate(taskDate);
					missProduct.setTaskId(taskId);
					missProduct.setParamCode(paramCode);
					list.add(missProduct);
					
				}
			}
			
		}
		
		return list;
	}
}
